package cn.jdy.plugins.service;

import cn.jdy.framework.db.hibernate.BaseDao;
import cn.jdy.framework.log.BaseLog;
import cn.jdy.plugins.entity.IPRecord;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Calendar;

/**
 * IP操作记录
 * Created by Heavens on 2014/9/8.
 */
@Service
@Transactional
public class IPRecordService extends BaseDao<IPRecord> {

	private static boolean flag = false;
	/**
	 * 查询今天是否已经上传过数据
	 * @param ip
	 * @return
	 */
	public boolean isOperatedToday(String ip, String operType) {
		return isOperatedToday(ip, operType, "ipv4");
	}

	/**
	 * 查询今天是否已经上传过数据
	 * @param ip
	 * @param ipType
	 * @return
	 */
	public boolean isOperatedToday(String ip, String operType, String ipType) {
		if(flag) {
			DetachedCriteria dc = DetachedCriteria.forClass(entityClass);
			dc.add(Restrictions.eq("ip", ip));
			dc.add(Restrictions.eq("ipType", ipType));
			dc.add(Restrictions.eq("operType", operType));
			Calendar calendar = Calendar.getInstance();
      calendar.set(Calendar.HOUR_OF_DAY, 0);
      calendar.set(Calendar.MINUTE, 0);
      calendar.set(Calendar.SECOND, 0);
      dc.add(Restrictions.gt("operDate", calendar.getTime()));
      return super.count(dc) > 0;
		}else
			return false;
	}

	/**
	 * 保存操作数据
	 * @param ip
	 * @param ipType
	 * @return
	 */
	public void save(String ip, String ipType, String operType) {
		try {
			IPRecord ipRecord = super.findOne("ip", ip, "ipType", ipType, "operType", operType);
			if(ipRecord == null) {
				ipRecord = new IPRecord();
				ipRecord.setIp(ip);
				ipRecord.setIpType(ipType);
				ipRecord.setOperType(operType);
				ipRecord.setOperDate(Calendar.getInstance().getTime());
				super.save(ipRecord);
			}else {
				ipRecord.setOperDate(Calendar.getInstance().getTime());
				super.update(ipRecord);
			}
		}catch(Exception e) {
			BaseLog.e(this.getClass(), "保存IP记录异常", e);
		}
	}

}
